import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import 'dayjs/locale/zh-tw'
import { Lang } from '@/enums'
import { useAppStore } from '@/store'

const TIME_FORMAT = 'HH:mm:ss'

const DAY_TIME = 24 * 60 * 60 * 1000
const HOUR_TIME = 60 * 60 * 1000
const MINUTE_TIME = 60 * 1000
const SECOND_TIME = 1000

function getDateFormat() {
	const appStore = useAppStore()
	return appStore.lang === Lang.zh ? 'YYYY/MM/DD' : 'DD/MM/YYYY'
}

function getDateTimeFormat() {
	return `${getDateFormat()} ${TIME_FORMAT}`
}

export function fmtDateLang(val: string | number | Date | undefined, format: string) {
	const appStore = useAppStore()
	let locale = ''
	switch (appStore.lang) {
		case Lang.zh:
			locale = 'zh-cn'
			break
		case Lang.zhTW:
			locale = 'zh-TW'
			break
		default:
			locale = 'en'
			break
	}
	return dayjs(val).locale(locale).format(format)
}

export function getFormatDateBaseLanguage() {
	const appStore = useAppStore()
	const lang = appStore.lang

	if (lang === Lang.zh) {
		return 'YYYY/MM/DD'
	}
	return 'DD/MM/YYYY'
}

export function dateFormat(val: any, format = getFormatDateBaseLanguage()) {
	return dayjs(val).format(format)
}

export function fmtDate(val: string | number | Date | undefined, format = getDateFormat()) {
	if (!val) {
		return ''
	}
	return dayjs(val).format(format)
}

export function fmtTime(val: string | number | Date | undefined, format = TIME_FORMAT) {
	return dayjs(val).format(format)
}

export function fmtDateTime(val: string | number | Date | undefined, format = getDateTimeFormat()) {
	return dayjs(val).format(format)
}

export function getLeftDateArr(val: number) {
	const d = Math.floor(val / DAY_TIME)
	const h = Math.floor((val % DAY_TIME) / HOUR_TIME)
	const m = Math.floor((val % HOUR_TIME) / MINUTE_TIME)
	const s = Math.floor(val / SECOND_TIME) % 60
	return {
		d,
		h,
		m,
		s
	}
}

export function getRelativeDateArr(val: any, now = Date.now()) {
	const value = new Date(val).valueOf()
	const sign = now > value
	const rel = Math.abs(now - value)
	const { d, h, m } = getLeftDateArr(rel)
	return {
		sign,
		d,
		h,
		m
	}
}

export const getBeforeDayTimes = (num: any, format = 'DD/MM') => {
	const dayAgoTime: any = dayjs().subtract(num, 'day')
	return dateFormat(dayAgoTime.$d, format)
}

export function fmtDateTimeGMT(
	val: string | number | Date | undefined,
	format = getDateFormat() + ' HH:mm:ss'
) {
	const offset = new Date().getTimezoneOffset() / 60
	const gmtStr = ' GMT' + (offset > 0 ? '-' : '+') + Math.abs(offset)
	return dayjs(val).format(format) + gmtStr
}
